<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>套餐公告管理</span>
        </div>
      </template>
      <el-form ref="packageNoticeRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="公告标题" prop="noticeTitle">
          <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="noticeContent">
          <el-input v-model="form.noticeContent" type="textarea" :rows="4" placeholder="请输入公告内容" />
        </el-form-item>
        <el-form-item label="套餐类型" prop="packageType">
          <el-select v-model="form.packageType" placeholder="请选择套餐类型">
            <el-option label="限时特惠" value="限时特惠"></el-option>
            <el-option label="新用户专享" value="新用户专享"></el-option>
            <el-option label="全部套餐" value="all"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客服二维码" prop="qrCodeUrl">
          <el-row>
            <el-col :span="12">
              <el-upload
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                accept="image/*"
                :on-change="handleFileChange"
              >
                <el-button type="primary">选择图片</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传JPG/PNG格式图片，大小不超过2MB
                  </div>
                </template>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <div class="image-preview" v-if="imageBase64">
                <img :src="imageBase64" class="preview-image" />
              </div>
              <div class="image-preview" v-else-if="form.qrCodeUrl && !imageBase64">
                <div class="qrcode-url">
                  <small>已保存路径: {{ form.qrCodeUrl }}</small>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-input v-if="form.qrCodeUrl" v-model="form.qrCodeUrl" readonly class="mt-10">
            <template #append>
              <el-button @click="copyToClipboard(form.qrCodeUrl)">
                <el-icon><CopyDocument /></el-icon> 复制
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="'0'">显示</el-radio>
            <el-radio :label="'1'">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 显示历史记录 -->
    <el-card class="box-card mt-20">
      <template #header>
        <div class="card-header">
          <span>历史公告</span>
        </div>
      </template>
      <el-table :data="noticeList" style="width: 100%" v-loading="loading">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column prop="noticeTitle" label="公告标题" />
        <el-table-column prop="packageType" label="套餐类型" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
              {{ scope.row.status === '0' ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qrCodeUrl" label="客服二维码" width="200">
          <template #default="scope">
            <el-popover
              placement="right"
              :width="200"
              trigger="hover"
              v-if="scope.row.qrCodeUrl"
            >
              <template #reference>
                <el-link type="primary">查看二维码</el-link>
              </template>
              <div class="qrcode-preview">
                <img :src="scope.row.qrCodeUrl.startsWith('http') ? scope.row.qrCodeUrl.replace(/ /g, '%20') : getImageUrl(scope.row.qrCodeUrl)" 
                     style="width: 100%; max-height: 180px;" 
                     @error="(e) => handleImageError(e, scope.row.qrCodeUrl)" alt="二维码" />
                <div v-if="scope.row.qrCodeUrl" class="qrcode-url">
                  <small>{{ scope.row.qrCodeUrl }}</small>
                </div>
              </div>
            </el-popover>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { CopyDocument } from '@element-plus/icons-vue';
import ImageUpload from '@/components/ImageUpload';
import ImagePreview from '@/components/ImagePreview';
import { listPackageNotice, getPackageNotice, addPackageNotice, updatePackageNotice, delPackageNotice } from "@/api/checksystem/packageNotice";

const { proxy } = getCurrentInstance();

// 图片预览基础URL
const baseImageUrl = import.meta.env.VITE_APP_BASE_API;

// Base64格式的图片数据
const imageBase64 = ref('');

// 表单数据
const formData = reactive({
  form: {
    id: undefined,
    noticeTitle: '',
    noticeContent: '',
    packageType: '',
    qrCodeUrl: '',
    orderNum: 0,
    status: '0',
  },
  rules: {
    noticeTitle: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
    packageType: [{ required: true, message: '请选择套餐类型', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  }
});

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  packageType: undefined
});

// 列表数据
const noticeList = ref([]);
const total = ref(0);
const loading = ref(false);

const { form, rules } = toRefs(formData);

/**
 * 获取历史公告列表
 */
function getList() {
  loading.value = true;
  listPackageNotice(queryParams.value).then(response => {
    noticeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    
    // 调试信息
    if (response.rows && response.rows.length > 0) {
      response.rows.forEach(row => {
        if (row.qrCodeUrl) {
          console.log('公告ID:', row.id);
          console.log('公告标题:', row.noticeTitle);
          console.log('二维码URL:', row.qrCodeUrl);
          console.log('是否为Base64格式:', isBase64Image(row.qrCodeUrl));
          console.log('完整图片路径:', getImageUrl(row.qrCodeUrl));
          console.log('-------------------');
        }
      });
    }
  }).catch(error => {
    console.error('获取套餐公告列表失败:', error);
    loading.value = false;
    // 模拟数据（仅在API失败时使用）
    noticeList.value = [
      {
        id: 1,
        noticeTitle: '限时活动通知',
        noticeContent: '新用户注册即送100积分',
        packageType: '限时特惠',
        qrCodeUrl: '/profile/upload/2023/04/01/qrcode_sample_20230401123456.png',
        orderNum: 1,
        status: '0',
        createTime: new Date()
      },
      {
        id: 2,
        noticeTitle: '系统维护通知',
        noticeContent: '系统将于本周日进行维护升级',
        packageType: 'all',
        qrCodeUrl: '',
        orderNum: 2,
        status: '1',
        createTime: new Date()
      }
    ];
    total.value = 2;
  });
}

/**
 * 提交表单
 */
function submitForm() {
  proxy.$refs.packageNoticeRef.validate(valid => {
    if (valid) {
      const isUpdate = form.value.id !== undefined;
      const apiCall = isUpdate 
        ? updatePackageNotice(form.value)
        : addPackageNotice(form.value);
      
      apiCall.then(response => {
        ElMessage.success(isUpdate ? '修改成功' : '新增成功');
        resetForm();
        getList();
      }).catch(error => {
        console.error('保存套餐公告失败:', error);
        ElMessage.error('操作失败，请重试');
      });
    }
  });
}

/**
 * 重置表单
 */
function resetForm() {
  proxy.$refs.packageNoticeRef.resetFields();
  form.value = {
    id: undefined,
    noticeTitle: '',
    noticeContent: '',
    packageType: '',
    qrCodeUrl: '',
    orderNum: 0,
    status: '0',
  };
  imageBase64.value = '';
}

/**
 * 编辑公告
 */
function handleEdit(row) {
  const id = row.id;
  getPackageNotice(id).then(response => {
    form.value = response.data;
    
    // 如果有二维码URL，则设置imageBase64
    if (form.value.qrCodeUrl) {
      if (isBase64Image(form.value.qrCodeUrl)) {
        imageBase64.value = form.value.qrCodeUrl;
      } else {
        // 如果不是Base64格式，尝试加载图片
        imageBase64.value = getImageUrl(form.value.qrCodeUrl);
      }
    }
  }).catch(error => {
    console.error('获取套餐公告详情失败:', error);
    // 备选方案：直接使用表格行数据
    form.value = JSON.parse(JSON.stringify(row));
    
    // 如果有二维码URL，则设置imageBase64
    if (form.value.qrCodeUrl) {
      if (isBase64Image(form.value.qrCodeUrl)) {
        imageBase64.value = form.value.qrCodeUrl;
      } else {
        // 如果不是Base64格式，尝试加载图片
        imageBase64.value = getImageUrl(form.value.qrCodeUrl);
      }
    }
  });
}

/**
 * 删除公告
 */
function handleDelete(row) {
  proxy.$modal.confirm('确认删除该公告吗？').then(() => {
    delPackageNotice(row.id).then(() => {
      ElMessage.success('删除成功');
      getList();
    }).catch(error => {
      console.error('删除套餐公告失败:', error);
      ElMessage.error('删除失败，请重试');
    });
  }).catch(() => {});
}

/**
 * 复制文本到剪贴板
 */
function copyToClipboard(text) {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('已复制到剪贴板');
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制');
  });
}

/**
 * 检查是否为Base64格式的图片
 */
function isBase64Image(str) {
  return typeof str === 'string' && str.startsWith('data:image');
}

/**
 * 检查图片是否存在
 */
function checkImageExists(url) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    img.src = url;
  });
}

/**
 * 获取图片URL
 */
function getImageUrl(path) {
  if (!path) return '';
  if (path.startsWith('http')) {
    // 确保URL中的空格被正确编码
    return path.replace(/ /g, '%20');
  }
  if (path.startsWith('data:image')) return path;
  
  // 打印原始路径，用于调试
  console.log('原始图片路径:', path);
  
  // 处理文件名中包含特殊字符的情况
  if (path.includes('%')) {
    path = decodeURIComponent(path);
  }
  
  // 使用相对路径访问
  // 确保路径以斜杠开头
  const normalizedPath = path.startsWith('/') ? path : '/' + path;
  
  // 确保URL中的空格被正确编码
  return (baseImageUrl + normalizedPath).replace(/ /g, '%20');
}

/**
 * 处理图片加载错误
 */
function handleImageError(e, url) {
  console.error('图片加载失败:', url);
  
  // 获取图片元素
  const imgElement = e.target;
  const originalSrc = imgElement.src;
  
  // 尝试不同的URL格式
  if (originalSrc.includes(' ')) {
    // 如果URL包含空格，尝试替换为%20
    const encodedSrc = originalSrc.replace(/ /g, '%20');
    console.log('尝试编码空格:', encodedSrc);
    imgElement.src = encodedSrc;
    return;
  }
  
  // 尝试使用不同的前缀
  const prefixes = [
    '/profile/',
    '/profile/upload/',
    '/profile/upload_',
    '/'
  ];
  
  // 提取文件名
  let fileName = url;
  const lastSlashIndex = url.lastIndexOf('/');
  if (lastSlashIndex !== -1) {
    fileName = url.substring(lastSlashIndex + 1);
  }
  
  // 尝试不同的前缀
  for (const prefix of prefixes) {
    const newPath = baseImageUrl + prefix + fileName;
    const encodedPath = newPath.replace(/ /g, '%20');
    console.log('尝试路径:', encodedPath);
    
    // 创建新的Image对象来测试URL是否有效
    const testImg = new Image();
    testImg.onload = function() {
      console.log('找到有效路径:', encodedPath);
      imgElement.src = encodedPath;
    };
    testImg.src = encodedPath;
  }
}

/**
 * 处理文件选择
 */
function handleFileChange(file) {
  const isImage = file.raw.type.indexOf('image/') !== -1;
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }

  // 读取文件并转换为Base64
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    // 显示Base64格式的图片
    imageBase64.value = reader.result;
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', file.raw);

    // 显示上传中提示
    ElMessage.info('正在上传图片，请稍候...');

    // 调用后端上传接口
    const xhr = new XMLHttpRequest();
    xhr.open('POST', baseImageUrl + '/common/service/upload', true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText);
          if (response.code === 200) {
            // 上传成功
            ElMessage.success('上传成功');
            
            // 保存文件路径
            if (response.fileName) {
              form.value.qrCodeUrl = response.fileName;
            } else if (response.url) {
              form.value.qrCodeUrl = response.url;
            }
            
            console.log('上传成功，文件路径:', form.value.qrCodeUrl);
            console.log('完整响应:', response);
          } else {
            // 上传失败
            ElMessage.error(response.msg || '上传失败');
          }
        } catch (e) {
          ElMessage.error('解析响应失败');
          console.error(e);
        }
      } else {
        ElMessage.error('上传失败，状态码: ' + xhr.status);
      }
    };
    
    xhr.onerror = function() {
      ElMessage.error('网络错误，上传失败');
    };
    
    xhr.send(formData);
  };
}

onMounted(() => {
  // 打印环境变量
  console.log('baseImageUrl:', baseImageUrl);
  console.log('VITE_APP_BASE_API:', import.meta.env.VITE_APP_BASE_API);
  
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mt-10 {
  margin-top: 10px;
}
.mt-20 {
  margin-top: 20px;
}
.image-preview {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 5px;
  text-align: center;
  margin-left: 20px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.preview-image {
  max-width: 100%;
  max-height: 140px;
}
.qrcode-preview {
  padding: 10px;
  text-align: center;
}
.qrcode-url {
  margin-top: 5px;
  text-align: center;
}
</style> 